package ch.il07.converter.persistance.tests;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import ch.il07.converter.persistence.Persistence;
import ch.il07.converter.persistence.PersistenceHelper;
import ch.il07.converter.persistence.entities.AccessLevel;
import ch.il07.converter.persistence.entities.Measurand;
import ch.il07.converter.persistence.entities.Unit;
import ch.il07.converter.persistence.exceptions.PersistenceException;
import ch.il07.converter.persistence.exceptions.UserAlreadyExistsException;
import ch.il07.utils.RandomHelper;

public class GetUserMeasurands {

	private Persistence persistence;

	@Before
	public void setUp() {
		try {
			persistence = PersistenceHelper.getPersistence();
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}
	}

	@Test
	public void zeroMeasurands() {
		String username = RandomHelper.randString();

		try {
			persistence.addUser(username, RandomHelper.getEmail(username), username,
					AccessLevel.USER);
			assertNotNull(persistence.getUser(username, username));
			assertTrue("user '" + username + "' shouldn't have any measurands",
					persistence.getMeasurands(username).size() == 0);
		} catch (UserAlreadyExistsException e) {
			fail(e.getMessage());
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}

	}

	@Test
	public void someMeasurands() {
		String username = RandomHelper.randString();

		try {
			persistence.addUser(username, RandomHelper.getEmail(username), username,
					AccessLevel.USER);
			assertNotNull("user '" + username + "' should have been created in db", persistence
					.getUser(username, username));

			Measurand m = new Measurand(RandomHelper.randString(), new Unit(RandomHelper.randString(), 1D));
			m.setOwner(persistence.getUser(username, username));
			m.addUnit(new Unit(RandomHelper.randString(), Math.random() * 50));
			m.addUnit(new Unit(RandomHelper.randString(), Math.random() * 50));
			m.addUnit(new Unit(RandomHelper.randString(), Math.random() * 50));
			m.addUnit(new Unit(RandomHelper.randString(), Math.random() * 50));
			
			persistence.addMeasurand(m, username);

			List<Measurand> measurands = persistence.getMeasurands(username);
			assertTrue("user '" + username + "' should have one measurand",
					measurands.size() == 1);

			Measurand theOne = measurands.get(0);
			assertTrue("measurand must have exactely 4 measurands but has " + theOne.getUnits().size(), theOne
					.getUnits().size() == 4);

		} catch (UserAlreadyExistsException e) {
			fail(e.getMessage());
		} catch (PersistenceException e) {
			fail(e.getMessage());
		} 
	}
}
